package com.waigoulin.infrastructure.adapter.port;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.waigoulin.domain.order.adapter.port.IPaymentPort;
import com.waigoulin.domain.order.model.entity.PayOrderEntity;
import com.waigoulin.domain.order.model.valobj.OrderStatusVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @FileName PaymentPort
 * @Description 订单服务基础设施层接口实现类
 * @Author waigoulin
 * @date 2025-07-31
 **/
@Service
public class PaymentPort implements IPaymentPort {

    @Value("${alipay.notify_url}")
    private String notifyUrl;

    @Value("${alipay.return_url}")
    private String returnUrl;

    @Resource
    private AlipayClient alipayClient;

    @Override
    public PayOrderEntity createPayment(String userId, String productId, String productName, String orderId, BigDecimal totalAmount) throws AlipayApiException {
        // 支付宝支付请求，设置回调链接和返回链接
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);

        // 设置订单具体参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        bizContent.put("total_amount", totalAmount.toString());
        bizContent.put("subject", productName);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        // 执行请求并解析响应
        String form = alipayClient.pageExecute(request).getBody();

        // 更新支付单对应的流水单
        return PayOrderEntity.builder()
                .userId(userId)
                .orderId(orderId)
                .payUrl(form)
                .orderStatus(OrderStatusVO.PAY_WAIT)
                .build();
    }

}


